package cn.zhxu.toys.bank;

import cn.zhxu.okhttps.HttpResult;
import cn.zhxu.okhttps.HttpUtils;
import cn.zhxu.data.Mapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 聚合四要素验证器
 * 
 * @author Troy.Zhou
 *
 */
public class JuheBankVerifier implements BankVerifier {

	static final Logger log = LoggerFactory.getLogger(JuheBankVerifier.class);
	
    //1:匹配 2:不匹配*
    static final int RESULT_MATCH = 1;
    static final int RESULT_NOT_MATCH = 2;
	
	
	static final String endpoint = "http://v.juhe.cn/verifybankcard4/query";
	
	
	private String appkey;
	
	
	public JuheBankVerifier() {
	}


	public JuheBankVerifier(String appkey) {
		super();
		this.appkey = appkey;
	}

/**
	//		名称	      	类型		必填	说明
	//		key     	string	是	您申请的key
	//		realname	string	是	姓名，需要utf8 Urlencode
	//		idcard	    string	是	身份证号码
	//		bankcard	string	是	银行卡卡号
	//		mobile	    string	是	手机号码
**/
	@Override
	public Result verify(String realName, String idCardNo, String bankPhone, String bankCardNo) {
		HttpResult result = HttpUtils.sync(endpoint)
				.addBodyPara("key", appkey)
				.addBodyPara("realname", realName)
				.addBodyPara("idcard", idCardNo)
				.addBodyPara("bankcard", bankCardNo)
				.addBodyPara("mobile", bankPhone)
				.post();
		if (!result.isSuccessful()) {
			log.error("聚合银行四要素返回状态码错误：" + result.getStatus());
			return Result.fail("聚合银行四要素返回状态码不是200！");
		}
		Mapper mapper = result.getBody().toMapper();
		if (mapper == null) {
			log.error("认证返回结果为空！");
			return Result.fail("认证返回结果为空！");
		}
		if (mapper.getInt("error_code") != 0) {
			return Result.fail(mapper.getString("reason"));
		}
		Mapper resJson = mapper.getMapper("result");
		if (resJson.getInt("res") == RESULT_MATCH) {
			return Result.ok();
		}
		return Result.fail(resJson.getString("message"));
	}


	public String getAppkey() {
		return appkey;
	}

	public void setAppkey(String appkey) {
		this.appkey = appkey;
	}
	

}
